#include <amxmodx>
#include <amxmisc>

#define MAXREC 256
#define MAXLEN 32

new ip_table[MAXREC][MAXLEN]
new ip_alias[MAXREC][MAXLEN]
new ip_num = 0


public plugin_init()
	{ 
	register_plugin("amx_who","0.99","Wonder") 
	register_concmd("amx_who","amx_who",ADMIN_LEVEL_C,"- displays who is on server")
	register_srvcmd("ip_descr","ip_descr")
	return PLUGIN_CONTINUE
	}

public ip_descr()
	{
	if (read_argc()!=3)
		{
		server_print("Usage: ip_alias <ip substring> <description>")
		return PLUGIN_HANDLED
		} 
	else if (ip_num>=MAXREC)
		{
		server_print("[amx_ip] The internal data structure is full.")
		return PLUGIN_HANDLED
		}
	else
		{
		new usrip[MAXLEN],alias[MAXLEN]
		read_argv(1, usrip, MAXLEN-1)
		read_argv(2, alias, MAXLEN-1)
		ip_table[ip_num] = usrip
		ip_alias[ip_num] = alias
		ip_num++
		server_print("[amx_ip] The ip %s (%s) has been added!", usrip, alias)
	}
	return PLUGIN_CONTINUE
}

public amx_who(id,level,cid)
	{ 
	if (!cmd_access(id,level,cid,1))
		return PLUGIN_HANDLED
	new uid,maxpl,pl
	new Name[MAXLEN] 
	new IP[MAXLEN]
	new authid[MAXLEN]
	new descr[MAXLEN]
	new players[32]
	new flags,sflags[32]
	new i,j
	console_print(id,"^nClients on server:^n%-6s %-24s %-16s %-20s %s %s","ID","Nick","IP","HDD","Description","access")
	get_players(players,maxpl)
	for (j=0;j<maxpl;j++)
		{
		pl=players[j]
		descr=""
		get_user_ip(pl,IP,MAXLEN-1,1)
		get_user_info(players[j], "*hwID", authid, 31)
		get_user_name(pl,Name,MAXLEN-1)
		flags=get_user_flags(players[j])
		get_flags(flags,sflags,31)
		uid=get_user_userid(pl)
		for(i=0;i<ip_num;i++)
			{
			if (contain(IP,ip_table[i])!=-1)
				{
		    		descr=ip_alias[i]
		    		break
				}
			if (is_ip_net(IP,ip_table[i]))
				{
		    		descr=ip_alias[i]
		    		break
				}
		    	}
		console_print(id,"%-6d %-24s %-16s %-20s %s %s",uid,Name,IP,authid,descr,sflags)
	}
	return PLUGIN_HANDLED 
} 

is_ip_net(const ip[MAXLEN],const ip_net[MAXLEN]) {
	if(contain(ip_net,"-")==-1) return 0
	new tempip[MAXLEN],net[MAXLEN]
	new i1[12],i2[12],i3[12],i4[12]
	tempip=ip_net
	while(replace(tempip, MAXLEN, ".", " ")){}
	replace(tempip, MAXLEN, ":", " ")
	parse(tempip,i1,12,i2,12,i3,12,i4,12)
	net=""
	add(net,MAXLEN,i1)
	add(net,MAXLEN,".")
	add(net,MAXLEN,i2)
	add(net,MAXLEN,".")
	add(net,MAXLEN,i3)
	add(net,MAXLEN,".")
	if (contain(ip, net) == -1) return 0
	if (contain(i4,"-") == -1) return 0
	replace(i4, 12, "-", " ")
	if (contain(i4,"-") != -1) return 0
	new d1[12],d2[12]
	parse(i4,d1,12,d2,12)
	new s1=str_to_num(d1)
	new s2=str_to_num(d2)
	if (s1>=s2) return 0
	tempip=ip
	while(replace(tempip, MAXLEN, ".", " ")){}
	replace(tempip, MAXLEN, ":", " ")
	parse(tempip,i1,12,i2,12,i3,12,i4,12)
	new s3=str_to_num(i4)
	if(s3>=s1 && s3<=s2) {
		return 1
	}
	return 0
}